/**
 * 绝对地址编辑接口测试用例
 *
 * Created by raquelmao on 2020/07/10.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const common = require('./../../../common');
const Administrator = require('./../../../../models/administrator');
const uri = require('./../../uri');
const benchmark = require('./../../../../benchmark/analyse-files/self_designed');
const utility = require('./../../../../../phoenix/models/utility');
const { fixedAddrBasesAssignmentKind } = require('./../../../../../phoenix/models/functions');

module.exports = describe('/PUT functions/:functionId/fixed-addresses/:fixedAddressName.json', function () {
  const administrator = new Administrator();
  const newUserIds = [];
  let projectVersion = {};
  let func = {};
  let testCaseId;
  function url(fixedAddressName, functionId) {
    if (!functionId) {
      functionId = func.functionId;
    }
    return `/functions/${functionId}/fixed-addresses/${fixedAddressName}.json`;
  }
  function addTestCaseUrl(functionId) {
    if (!functionId) {
      functionId = func.functionId;
    }
    return `/functions/${functionId}/tests.json`;
  }
  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((res) => {
        projectVersion = res;
        return projectVersion.getAllFunctions(benchmark);
      })
      .then(([item]) => {
        func = item;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'put');
  common.should.be.tester(uri, url, 'put');
  common.should.be.tester(uri, addTestCaseUrl, 'post');

  // 给函数添加一个测试用例
  it('it should ADD test case', function (done) {
    chai.request(uri)
      .post(addTestCaseUrl(func.functionId))
      .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
      .send({ data: {} })
      .end((err, res) => {
        res.should.have.status(200);
        testCaseId = res.body.testId;
        done();
      });
  });
  // 正常编辑
  [
    { fixedAddressName: `0x${Math.floor(Math.random() * 100000000).toString(16)}`, length: '10', pointerTargets: { '偏移量 1': { '@type': '', '@length': '19', '@elementType': 'int' } } },
    { fixedAddressName: `0x${Math.floor(Math.random() * 100000000).toString(16)}`, pointerTargets: { '偏移量 1': { '@type': '', '@length': '19', '@elementType': 'int' } } },
    { fixedAddressName: `0x${Math.floor(Math.random() * 100000000).toString(16)}` },
  ].forEach((variable, index) => {
    it(`it should ${index === 0 ? 'EDIT' : 'edit'} fixed address`, function (done) {
      const { fixedAddressName, length, pointerTargets } = variable;
      func.addFixedAddressVariable(fixedAddressName, length, pointerTargets)
        .then(() => {
          const newVariable = {
            newName: `0x${Math.floor(Math.random() * 100000000).toString(16)}`, assignmentKind: fixedAddrBasesAssignmentKind.baseOffset, length: '10', pointerTargets: { '偏移量 1': { '@type': '', '@length': '10', '@elementType': 'int' } },
          };
          // 编辑
          chai.request(uri)
            .put(url(variable.fixedAddressName, func.functionId))
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .send({ ...newVariable, testCaseId })
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.functionFixedAddressMessage(res.body);
              res.body.functionId.should.be.eql(func.functionId);
              res.body.fixedAddressName.should.be.eql(utility.convertHexToDec(newVariable.newName));
              if (newVariable.pointerTargets) {
                const { pointerTargets } = newVariable;
                Object.keys(pointerTargets).forEach((offset) => {
                  res.body.pointerTargets.should.have.property(offset);
                });
              }
              done();
            });
        })
        .catch(done);
    });
  });

  const originName = `0x${Math.floor(Math.random() * 100000000).toString(16)}`;
  const otherName = `0x${Math.floor(Math.random() * 100000000).toString(16)}`;
  // 无法编辑成已有的绝对地址名
  const originVariable = { fixedAddressName: originName, pointerTargets: { '偏移量 2': { '@type': '', '@length': '19', '@elementType': 'int' } } };
  const otherOriginVariable = { fixedAddressName: otherName, pointerTargets: { '偏移量 2': { '@type': '', '@length': '19', '@elementType': 'int' } } };
  const newVariable = {
    newName: otherName, length: '10', assignmentKind: fixedAddrBasesAssignmentKind.baseOffset, pointerTargets: { '偏移量 1': { '@type': '', '@length': '10', '@elementType': 'int' } },
  };
  it('it should fail to edit fixed address name when it exists', function (done) {
    let functionId;
    const { fixedAddressName, length, pointerTargets } = originVariable;
    func.addFixedAddressVariable(fixedAddressName, length, pointerTargets)
      .then(() => {
        const { fixedAddressName, length, pointerTargets } = otherOriginVariable;
        return func.addFixedAddressVariable(fixedAddressName, length, pointerTargets);
      })
      .then(() => {
        // 编辑
        chai.request(uri)
          .put(url(originVariable.fixedAddressName, functionId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({ ...newVariable, testCaseId })
          .end((err, res) => {
            res.should.have.status(409);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
